function dataURLtoFile(dataurl, filename = 'file') {
      let arr = dataurl.split(',')
      let mime = arr[0].match(/:(.*?);/)[1]
      let suffix = mime.split('/')[1]
      let bstr = atob(arr[1])
      let n = bstr.length
      let u8arr = new Uint8Array(n)
      while (n--) {
          u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], `${filename}.${suffix}`, {
          type: mime
      })
}

// 获取base64的文件类型
function getBase64Mine(dataurl) {
  let arr = dataurl.split(',')
  let mime = arr[0].match(/:(.*?);/)[1];
  let suffix = mime.split('/')[1];
  return suffix;
}

function getToday() {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    month = parseInt(month) < 10 ? `0${month}` : month;
    day = parseInt(day) < 10 ? `0${day}` : day;
    return `${year}${month}${day}`;
}

function setToday() {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    document.getElementById('today-small').innerHTML = `今天是 ${year}年${month}月${day}日`;
}
setToday();


const zip = new JSZip();

const Vm = new Vue({
    el: '#app',
    data() {
        return {
            // 原始图片
            imageBase64: '',
            imageFile: null,
            pieces: 8,
            showWaiting: false,
            zipname: 'images',
            ztTitle: '',
            ztDesc: '',
            imgInfo: '',
            imgObj: null,
            // 存放所有切图
            imgs: [],
            // 存放原始图以及分享图
            imgOther: {
                origin: {},
                share: {}
            },
            showCopper: false
        }
    },
    mounted() {
        document.getElementById('loading').style.display = 'none';
    },
    methods: {
        reset() {
            window.location.reload();
        },
        addTodayStr() {
            if (this.zipname.indexOf('-') > -1) {
                this.zipname = this.zipname.replace('-', '');
            }
            let time = getToday();
            let zipname = this.zipname;
            zipname = zipname.replace(/[\d]*/g, '');
            this.zipname = `${zipname}${time}`;
        },
        addRandomSuffix() {
            let rand = Math.floor(Math.random() * 100);
            if (rand < 10) {
                rand = (rand + 1) * 10;
            }
            let zipname = this.zipname;
            zipname = zipname.replace(/\-\d{2}/g, '');
            this.zipname = `${zipname}-${rand}`;
            console.log(rand);
        },
        listeningIframe() {
            if (!this.showCopper) {
                return;
            }
            window.addEventListener('message', (e) => {
                console.log(e)
                console.log(e.data);
                let base64 = e.data;
                let suffix = getBase64Mine(base64);
                let data = base64.substring(base64.indexOf(",") + 1);
                this.imgOther.share = {
                    filename: `share.${suffix}`,
                    // 用于插入到页面
                    base64: base64,
                    // 用于保存生成图片png
                    img64: data
                };
                this.closeCopper();
            }, false);
        },
        openCopperShare() {
            this.showCopper = true;
            const iframe = document.getElementById('iframe');
            iframe.src = IFRAME_SRC;

            iframe.contentWindow.postMessage(this.imageBase64, "*");
            console.log(iframe.contentWindow)
        },
        closeCopper() {
            this.showCopper = false;
        },
        async selectImgs(e) {
            this.showWaiting = true;
            const files = Array.from(e.target.files);
            const file = files[0];
            this.imageFile = file;
            console.log(this.imageFile);
            // 获取文件的base64格式
            this.imageBase64 = await this.readFile(file);
            // 将原始图存入压缩包
            this.saveOrigin();

            this.loadedImg();
        },
        loadedImg() {
            let image = new Image();
            image.src = this.imageBase64;
            image.addEventListener('load', () => {
                let info = `图片宽：${image.width}px<br>图片高： ${image.height}px<br>图片名称：${this.imageFile.name}<br>图片类型：${this.imageFile.type}<br>图片大小：${this.imageFile.size}<br>最后修改时间：${this.imageFile.lastModifiedDate}`;
                this.imgInfo = info;
                this.imgObj = image;
                // console.log(info)
                // 切割图片
                this.splitImg();       
            });
        },
        // 切割图片
        splitImg() {
            if (!this.imgObj) {
                window.alert('还未选择要切割的图片');
                return;
            }
            if (this.pieces <= 0) {
                window.alert('输入正确的切割份数！');
                return;
            }
            const image = this.imgObj;
            const pieces = this.pieces;

            let itemH = Math.ceil((image.height) / pieces);
            let itemW = image.width;

            // console.log(c.width, c.height)
            // ctx.clearRect(0, 0, c.width, c.height);

            for (var i = 0; i < pieces; i++) {
                let c = document.createElement('canvas');
                c.width = itemW;
                c.height = itemH;
                let ctx = c.getContext('2d');
                // document.body.appendChild(c);
                ctx.drawImage(image, 0, itemH * i, itemW, itemH, 0, 0, itemW, itemH);

                const base64 = c.toDataURL('image/png');
                 // 处理base64
                let data = base64.substring(base64.indexOf(",") + 1);
                const filename = `${i}.png`;
                let img = {
                    filename: filename,
                    // 用于插入到页面
                    base64: base64,
                    // 用于保存生成图片png
                    img64: data
                }

                this.imgs.push(img);

               
                // 将图片放入压缩包
                zip.file(filename, data, {base64: true});

                if (this.imgs.length == pieces) {
                    setTimeout(() => {
                        window.alert('图片均已经准备完毕，可以打包了。最好自定义分享图！');
                        this.showWaiting = false;
                    }, 500);   
                   
                }
            }

        },
        readFile(file) {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            return new Promise((resolve, reject) => {
                reader.onload = function(){                 
                    // console.log(this.result)  
                    // 返回base64格式的数据
                    const result = this.result;
                    //读取完成后，数据保存在对象的result属性中
                    resolve(result);
                };
                reader.onerror = function() {
                    reject(false);
                };
            });
        },
        // 保存原始图片
        saveOrigin() {
            let data = this.imageBase64.substring(this.imageBase64.indexOf(",") + 1);
            let suffix = this.imageFile.name.split('.')[1];
            let filename = `tp.${suffix}`;
            // 将原始图片放入压缩包
            zip.file(filename, data, {base64: true});
            // 存储信息
            this.imgOther.origin = {
                filename: filename,
                // 用于插入到页面
                base64: this.imageBase64,
                // 用于保存生成图片png
                img64: data
            }
        },
        saveShare() {
            // http://m.qdxin.cn/img/logofen170309.png
            if (this.imgOther.share.img64) {
                zip.file(
                    this.imgOther.share.filename, 
                    this.imgOther.share.img64, 
                    {base64: true}
                );
            } else {
                this.imgOther.share.filename = 'http://m.qdxin.cn/img/logofen170309.png';
            }
        },
        // 保存广告专题的HTML
        saveHtml() {
            let imgList = '';
            this.imgs.forEach((item, index) => {
                imgList += `<img src="${item.filename}" style="display: block;">`;
            });
            let indexPageStr = getIndexHtml({
                title: this.ztTitle,
                desc: this.ztDesc,
                share: this.imgOther.share.filename,
                imglist: imgList
            });

            let tpPageStr = getTpHtml({
                title: this.ztTitle,
                desc: this.ztDesc,
                origin: this.imgOther.origin.filename
            });


            zip.file('index.html', indexPageStr);
            zip.file('tp.html', tpPageStr);
        },
        saveZip() {
            if (this.imgs.length <= 0) {
                window.alert('切片图片不能为空！');
                return;
            }
            if (!this.imageBase64) {
                window.alert('请先上传长图！');
                return;
            }

            this.showWaiting = true;
            const zipname = this.zipname;

            this.saveShare();
            this.saveHtml();

            zip.generateAsync({
                    type: "blob",  // 压缩类型
                    compression: "DEFLATE",      // STORE：默认不压缩 DEFLATE：需要压缩
                    compressionOptions: {
                        level: 9  // 压缩等级1~9    1压缩速度最快，9最优压缩方式
                        // [使用一张图片测试之后1和9压缩的力度不大，相差100字节左右]
                    }
            })
            .then((content) => {
                    // 压缩的结果为blob类型（二进制流）,可用作文件上传
                    // console.info(content);
                    // 直接在浏览器打成car.zip包并下载，saveAs依赖的js是FileSaver.js
                    saveAs(content, zipname);
                    window.alert('资源包打包成功！');
                    this.showWaiting = false;
            });      
        }
    },
    components: {

    }
});


function getIndexHtml(obj) {
    const tpl = `
        <!DOCTYPE HTML>
        <html>
            
            <head>
                <meta charset="utf-8">
                <meta content="width=device-width,user-scalable=no" name="viewport">
                <meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE">
                <meta http-equiv="Cache-Control" content="no-cache" />
                <meta name="apple-mobile-web-app-capable" content="yes">
                <title>
                    ${obj.title}
                </title>
                <meta name="description" content="${obj.desc}">
                <!--#include file="/navmenu/gaolink2017.html"-->
            </head>
            
            <body>
                <!--#include file="/navmenu/gaohead2017.html"-->
                <img src="${obj.share}" id="sharelogo">
                </img>
                <!-- content -->
                <div class="kuanD1000 kongtop10 mkong40" id="kuanD">
                    <!-- editQ -->
                    <a href="tp.html" target="_blank" title="点击查看大图" class="pcshow">
                        <p class="imgbox">
                            ${obj.imglist}
                        </p>
                        <p class="picShow">
                            原图
                        </p>
                    </a>
                    <!-- editQ end-->
                    <!-- readNo -->
                    <div class="readNo">
                        <p>
                            阅读：
                            <span>
                                <script language="javascript" type="text/javascript" src="http://statics.qdxin.cn/api/dispcount.php?id=20170420&c=1&m=13">
                                </script>
                            </span>
                        </p>
                    </div>
                    <!-- readNo end -->
                    <!--#include file="/navmenu/gaobottom2017.html"-->

        </html>
    `;
    return tpl;
}

function getTpHtml(obj) {
    const tpl = `
        <!DOCTYPE html>
        <html>
            <head>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
                <meta content="width=device-width,user-scalable=no" name="viewport">
                <title>
                    ${obj.title}
                </title>
                <meta name="description" content="${obj.desc}">
            </head>
            
            <body>
                <img src="${obj.origin}">
            </body>

        </html>
    `;
    return tpl;
}